package com.jinzhi.jzweb.controller;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.ExaminationBatchComDO;
import com.jinzhi.jzweb.domain.ExaminationBatchDO;
import com.jinzhi.jzweb.domain.ExaminationPaperDO;
import com.jinzhi.jzweb.domain.ExaminationQuestionsDO;
import com.jinzhi.jzweb.service.ExaminationBatchComService;
import com.jinzhi.jzweb.service.ExaminationBatchService;
import com.jinzhi.jzweb.service.ExaminationPaperService;
import com.jinzhi.jzweb.service.ExaminationQuestionsService;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 
 * <pre>
 * 考试试卷
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationPaper")
public class ExaminationPaperController extends BaseController {
	@Autowired
	private ExaminationPaperService examinationPaperService;
	@Autowired
	private UserService userService;
	@Autowired
	private ExaminationBatchComService examinationBatchService;
	@Autowired
	private ExaminationQuestionsService examinationQuestionsService;
	
	@GetMapping()
	@RequiresPermissions("jzweb:examinationPaper:examinationPaper")
	String ExaminationPaper(){
	    return "jzweb/examinationPaper/examinationPaper";
	}
	
	@ResponseBody
	@GetMapping("/list")
	@RequiresPermissions("jzweb:examinationPaper:examinationPaper")
	public Result<Page<ExaminationPaperDO>> list(ExaminationPaperDO examinationPaperDTO){
		Wrapper<ExaminationPaperDO> wrapper = new EntityWrapper<ExaminationPaperDO>().orderBy("id", false);
		if (examinationPaperDTO.getState() != null){
			wrapper.eq("state",examinationPaperDTO.getState());
		}
		if (examinationPaperDTO.getNumbers() != null){
			wrapper.like("numbers",examinationPaperDTO.getNumbers());
		}
		if (examinationPaperDTO.getName() != null){
			wrapper.like("name",examinationPaperDTO.getName());
		}
		if (StringUtils.isNotBlank(examinationPaperDTO.getEbatchName())){
			Wrapper<ExaminationBatchComDO> exWrapper = new EntityWrapper<ExaminationBatchComDO>().like("name",examinationPaperDTO.getEbatchName());
			List<ExaminationBatchComDO>  examinationBatchDOS = examinationBatchService.selectList(exWrapper);
			String str = "";
			for (ExaminationBatchComDO examinationBatchDO : examinationBatchDOS){
				str = str + examinationBatchDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("ebatch_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("ebatch_id",null);
			}
		}

		Page<ExaminationPaperDO> page = examinationPaperService.selectPage(getPage(ExaminationPaperDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationPaperDO obj = (ExaminationPaperDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getCheckerId() != null){
				UserDO userDO = userService.selectById(obj.getCheckerId());
				if (userDO != null) {
					obj.setCheckerName(userDO.getUsername());
				}
			}
			if (obj.getEbatchId() != null){
				ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(obj.getEbatchId());
				if (examinationBatchDO != null) {
					obj.setEbatchName(examinationBatchDO.getName());
				}
			}
			list.add(obj);
		}
		page.setRecords(list);
        return Result.ok(page);
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:examinationPaper:add")
	String add(){
	    return "jzweb/examinationPaper/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:examinationPaper:edit")
	String edit(@PathVariable("id") Long id,Model model){
		ExaminationPaperDO examinationPaper = examinationPaperService.selectById(id);
		model.addAttribute("examinationPaper", examinationPaper);
	    return "jzweb/examinationPaper/edit";
	}

	@Log("添加考试试卷")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:examinationPaper:add")
	public Result<String> save( ExaminationPaperDO examinationPaper){
		examinationPaper.setCreaterId(this.getUserId());
		examinationPaperService.insert(examinationPaper);
        return Result.ok();
	}
	
	@Log("修改考试试卷")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:examinationPaper:edit")
	public Result<String>  update( ExaminationPaperDO examinationPaper){
		boolean update = examinationPaperService.updateById(examinationPaper);
		return update ? Result.ok() : Result.fail();
	}

	@Log("清除试卷缓存")
	@ResponseBody
	@RequestMapping("/clearCache")
	@RequiresPermissions("jzweb:examinationPaper:edit")
	public Result<String>  clearCache(Long id){
		ExaminationPaperDO epaper = examinationPaperService.selectById(id);
		ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(epaper.getEbatchId());
		if(examinationBatchDO==null){
			return Result.fail();
		}
		EhCacheUtil.remove("examinationPaperDO"+examinationBatchDO.getId());
		return Result.ok("清除成功");
	}
	
	@Log("删除考试试卷")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationPaper:remove")
	public Result<String>  remove( Long id){
		//修改考试批次状态
		ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(id);
		if(examinationPaperDO.getEbatchId() != null){
			ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(examinationPaperDO.getEbatchId());
			if(examinationBatchDO != null){
				if(examinationBatchDO.getState() == 3 || examinationBatchDO.getState() == 4 || examinationBatchDO.getState() == 5 || examinationBatchDO.getState() == 9){
					return Result.fail("根据当前试卷的考试批次状态判断，试卷不允许删除！");
				}else{
					examinationBatchDO.setState(1);
					examinationBatchService.updateById(examinationBatchDO);

					//删除考试试题
					List<ExaminationQuestionsDO> examinationQuestionsDOS = examinationQuestionsService.findByKv("epaper_id",id);
					if(examinationQuestionsDOS != null &&examinationQuestionsDOS.size() > 0){
						List<Long> ids = new ArrayList<>();
						for(int j=0;j<examinationQuestionsDOS.size();j++){
							ids.add(examinationQuestionsDOS.get(j).getId());
						}
						examinationQuestionsService.deleteBatchIds(ids);
					}

					//删除考试试卷
					examinationPaperService.deleteById(id);
				}
			}

		}

        return Result.ok();
	}
	
	@Log("批量删除考试试卷")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationPaper:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		if(ids != null && ids.length > 0){
			for(int i=0;i<ids.length;i++){
				ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(ids[i]);
				if(examinationPaperDO.getEbatchId() != null){
					ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(examinationPaperDO.getEbatchId());
					if(examinationBatchDO != null){
						if(examinationBatchDO.getState() == 3 || examinationBatchDO.getState() == 4 || examinationBatchDO.getState() == 5 || examinationBatchDO.getState() == 9){
							return Result.fail("根据当前试卷的考试批次状态判断，试卷不允许删除！");
						}else{
							examinationBatchDO.setState(1);
							examinationBatchService.updateById(examinationBatchDO);

							//删除考试试题
							List<ExaminationQuestionsDO> examinationQuestionsDOS = examinationQuestionsService.findByKv("epaper_id",ids[i]);
							if(examinationQuestionsDOS != null &&examinationQuestionsDOS.size() > 0){
								List<Long> idss = new ArrayList<>();
								for(int n=0;n<examinationQuestionsDOS.size();n++){
									idss.add(examinationQuestionsDOS.get(n).getId());
								}
								examinationQuestionsService.deleteBatchIds(idss);
							}
						}
					}
				}
			}
			examinationPaperService.deleteBatchIds(Arrays.asList(ids));
		}

		return Result.ok();
	}

	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationPaper:review")
	public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state,String remark){
		if (state.equals(2) || state.equals(1)) {
			int i = 0;
			for (Long id : ids) {
				ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(id);
				if(examinationPaperDO != null){
					examinationPaperDO.setState(state);
					examinationPaperDO.setCheckerId(this.getUserId());
					examinationPaperDO.setCheckerDate(new Date());
					if(state.equals(2)){
						examinationPaperDO.setRemark(remark);//未通过，添加备注
					}else{
						examinationPaperDO.setRemark("");//审核通过，清空备注
					}
					boolean b = examinationPaperService.updateById(examinationPaperDO);
					if (b) {
						i++;
					} else {
						break;
					}
				}
			}
			if (i == ids.length) {
				return Result.build(0,"已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}
		} else {
			return Result.fail("审核状态修改失败！");
		}
	}
}
